package com.habdqn.easybuy.web.manage.product.category;

import com.habdqn.easybuy.entity.ProductCategory;
import com.habdqn.easybuy.entity.User;
import com.habdqn.easybuy.service.ProductCategoryService;
import com.habdqn.easybuy.service.impl.ProductCategoryServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/28
 */
@WebServlet(name = "ProductCategoryAddServlet", urlPatterns = "/manage/product/category/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setName(request.getParameter("name"));
        String strParentId = request.getParameter("parentId");
        if (StringUtils.isNotBlank(strParentId)) {
            productCategory.setParentId(Integer.parseInt(strParentId));
        }

        ProductCategoryService productCategoryService = new ProductCategoryServiceImpl();
        if (productCategoryService.insert(productCategory).getId() != null) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("<script>");
            out.println("alert('新增分类成功！');");
            out.println("location.href='" + request.getContextPath() + "/manage/product/category';");
            out.println("</script>");
        } else {
            request.setAttribute("errorMsg", "新增失败");
            doGet(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取顶级分类
        List<ProductCategory> categories = new ProductCategoryServiceImpl().queryByParentId(0);
        request.setAttribute("categories",categories);
        request.getRequestDispatcher("/WEB-INF/manage/product/category-add.jsp").forward(request, response);
    }
}
